using System;
using System.Collections.Generic;
using System.Text;
using ImagesMath;

namespace Graphics.Geometries
{
    public class Cone : Form
    {
        public Cone() : base() { }

        public override bool FirstIntersection(ref Ray ray, ref Intersection inter)
        {
            bool Intersection = false;

            VR3 direction = ray.Direction;
            PR3 origine = ray.Origin;

            double Aq = direction.X * direction.X + direction.Y * direction.Y - direction.Z*direction.Z;
            double Bq = 2.0 * (direction.X * origine.X + direction.Y * origine.Y - -direction.Z * origine.Z);
            double Cq = origine.X * origine.X + origine.Y * origine.Y - origine.Z*origine.Z;
            double delta = (Bq * Bq - 4 * Aq * Cq);

            if (Aq != 0)
            {
                if (delta > ImageMath.EPS)
                {
                    double t1 = (-Bq - Math.Sqrt(delta)) / (2 * Aq);
                    double t2 = (-Bq + Math.Sqrt(delta)) / (2 * Aq);

                    if ((t1 < t2) && (IsInside(ray.ExtractPosition(t1))) && (t1 > ImageMath.EPS))
                    {
                        inter.T = t1;
                        Intersection = true;
                    }
                    else if (IsInside(ray.ExtractPosition(t2)) && (t2 > ImageMath.EPS))
                    {
                        inter.T = t2;
                        Intersection = true;
                    }
                }

            }
            else if (Bq != 0)
            {
                double t4 = -Cq / Bq;
                if ((t4 > ImageMath.EPS) && (IsInside(ray.ExtractPosition(t4))))
                {
                    //cout << "t4 : " << t4 << endl;
                    inter.T = t4;
                    Intersection = true;
                }
            }

            return Intersection;
        }
        public override VR3 Normal(PR3 p, ref Ray ray)
        {
            // vR3 vecteur(p.x, p.y, -p.z);
            //return (vecteur.normalize());
            VR3 vecteur = new VR3(p.X, p.Y, -p.Z);
            return (vecteur.normalize());
        }
        public override bool IsInside(PR3 p)
        {
            //return ((p.x*p.x + p.y*p.y - p.z*p.z <= EPS) && ( 0<=p.z ) && ( p.z<=10 ));
            return ((p.X * p.X + p.Y * p.Y - p.Z*p.Z <= ImageMath.EPS) && (0 <= p.Z) && (p.Z <= 10));
        }

        public override string getName()
        {
            return this.nomObjet;
        }
        public override void setName(string name)
        {
            this.nomObjet = name;
        }
    }
}
